package com.youchuang.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Repository;

import com.youchuang.bean.User;
import com.youchuang.common.HibernateConnection;
import com.youchuang.dao.UserDAO;

@Repository("userDAO")
public class UserDAOImpl implements UserDAO {

	private static final String HQL_FIND_BY_EMAIL = "from User where email = :email";
	private static final String HQL_FIND_BY_ID = "from User where id = :id";
	private static final String HQL_FIND_ALL = "from User";

	@Resource
	private HibernateConnection<User> hibernateConnection;

	public void save(User object) {
		hibernateConnection.save(object);
	}

	public void delete(User object) {
		//Do nothing because of it unusual
	}

	public int update(User object) {
		hibernateConnection.update(object);
		return 1;
	}

	public User queryByEmail(String email) {
		Map<String, Object> params = new HashMap<>();
		params.put("email", email);
		List<User> list = hibernateConnection.find(HQL_FIND_BY_EMAIL, params);
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		return list.get(0);
	}

	public User queryById(String id) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", id);
		List<User> list = hibernateConnection.find(HQL_FIND_BY_ID, params);
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		return list.get(0);
	}

	public List<User> queryAll() {
		return hibernateConnection.find(HQL_FIND_ALL);
	}

}
